import axios, { AxiosRequestConfig,AxiosInstance,AxiosResponse } from 'axios';
import { Message } from 'element-ui'
import Status from "@/domain/Status"

// let proxy:AxiosProxyConfig={host:'www.baidu.com',port:80};

let option:AxiosRequestConfig= {timeout:6000}; 

let install:AxiosInstance=axios.create(option);

// 请求拦截
install.interceptors.request.use((req:AxiosRequestConfig):AxiosRequestConfig=>{
    let token:string|null = localStorage.getItem('token');
    
    if(token){
        req.headers.Authorization=token;
    }

    return req;
},(error:any):any=>{

    console.error('请求异常：'+error);
    return Promise.reject(error);})

// 响应拦截
install.interceptors.response.use((resp:AxiosResponse):AxiosResponse=>{

    if(resp.data.status!=Status.SUCCESS){


        if(resp.data.msg){
            Message({ type: 'error', message:resp.data.msg });
        }
       throw  Error("服务器异常请联系管理员");
    }
    let axiosResp:AxiosResponse={...resp};
    axiosResp.data=resp.data.data;

    return axiosResp;
},(error:any):any=>{
    if(error.response&&error.response.status==404){
        Message({ type: 'error', message:`未发现资源path=${error.request.responseURL}` });
    }else{
        Message({ type: 'error', message: '服务器异常请联系管理员' });
    }
    return Promise.reject(error);
})

export default install;